#include "StdAfx.h"
#include "DbBase.h"
#include "Utils.h"

const UINT CDbBase::FIRST_RECORD_ID = 1;

CDbBase::CDbBase(CString DbName, UINT RecordSize)
    : m_DbName(DbName)
    , m_RecordSize(RecordSize)
{
}

CDbBase::~CDbBase(void)
{
    Close();
}

DWORD CDbBase::Open(void)
{
    CString DbFile;
    DWORD Err = GetDbFile(&DbFile);     // Also checks m_DbName.IsEmpty()
    if (Err != ERROR_SUCCESS)
        return Err;

    return m_DbMgr.Open(DbFile, m_RecordSize);
}

void CDbBase::Close(void)
{
    m_DbMgr.Close();
}

UINT CDbBase::GetCount(void)
{
    UINT Count = 0;
    DWORD Err = m_DbMgr.GetRecordCount(&Count);
    if (Err == ERROR_SUCCESS)
        return Count;

    return UINT_MAX;    // Error
}

bool CDbBase::Exists(void)
{
    CString DbFile;
    DWORD Err = GetDbFile(&DbFile);     // Also checks m_DbName.IsEmpty()
    if (Err != ERROR_SUCCESS)
    {
        ATLASSERT(!_T("Unable to get DB file"));
        return false;
    }

    CFindFile File;
    return File.FindFile(DbFile) == TRUE ? true : false;
}

DWORD CDbBase::GetDbFile(CString *pDbFile)
{
    ATLASSERT(pDbFile != NULL);

    if (m_DbName.IsEmpty() == true)
        return ERROR_INVALID_STATE;

    DWORD Err = Utils::GetFileFromModulePath(
        GetModuleHandle(NULL),
        pDbFile->GetBuffer(MAX_PATH),
        MAX_PATH,
        m_DbName);
    pDbFile->ReleaseBuffer();

    return Err;
}
